#!/usr/bin/python

import psycopg2
import psycopg2.extras

preparedStatementFactories = {
'Get Character Base Info and Abilities from Primary Key' : """

PREPARE getCharacterFromPk (integer) AS 
SELECT * FROM character
WHERE pk_character = $1;
""",
'Get Character Primary Key from Character Name pattern' : """

PREPARE getCharacterPkFromCharacterName (varchar) AS
SELECT pk_character FROM character
WHERE character_name ILIKE $1;
""",
'Get Character Primary Key from Player Name pattern' : """

PREPARE getCharacterPkFromPlayerName (varchar) AS
SELECT pk_character FROM character
WHERE player_name ILIKE $1;
""",
'Get Ability rows from Character Primary Key' : """

PREPARE getAbilsFromCharPk (integer) AS
SELECT * from ability a
LEFT JOIN abildef d ON a.fk_abildef = d.pk_abildef
""",
'Get Attack rows from Character Primary Key' : """

PREPARE getAttacksFromCharPk (integer) AS
SELECT * FROM attack WHERE fk_character = $1;
"""
}

def cleanquotes(val):
    if val is None: return ''
    return str(val).replace("'","\\'").replace('"','\\"')

conn = psycopg2.connect("dbname=postgres user=postgres")
dict_cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

# set up prepared statements (only valid per session)
for psf in preparedStatementFactories:
    dict_cur.execute(preparedStatementFactories[psf]);


# Fetch character primary key from a player name substring
dict_cur.execute("execute getCharacterPkFromPlayerName(%s)", ('%jer%',))
pk_character = dict_cur.fetchone()['pk_character'];


# Fetch character base attack bonus; interpolate into setter string
dict_cur.execute("execute getCharacterFromPk(%s)",(pk_character,))
char = dict_cur.fetchone();

fieldsFromDB = [ 'bab' ]
abilCombatString = ''
for f in fieldsFromDB:
    abilCombatString += """
    setValueById('%s', '%s');""" % (f, cleanquotes(char[f]) )


# Fetch character ability info; populate corresponding GUI elements
dict_cur.execute("execute getAbilsFromCharPk(%s)", (pk_character,))

abilsrcs = ['base', 'race', 'enh', 'misc'];
fieldsFromDB = [];
for i in range(dict_cur.rowcount):
    abil = dict_cur.fetchone()
    pre = cleanquotes(abil['abil'])
    for src in abilsrcs:
        abilCombatString += """
        setValueById('%s', '%s');""" % (pre + '_' + src, cleanquotes(abil[src]))


# Fetch character attack info; create GUI per attack and populate with setters
dict_cur.execute("execute getAttacksFromCharPk(%s)", (pk_character,))

fieldsFromDB = [ 'weap', 'enh', 'dmg', 'crit', 'range', 'dmgtype', 'ammo' ]
attackString = ''
for i in range(dict_cur.rowcount):
    attack = dict_cur.fetchone()
    attackString += """
    document.getElementById('addAttackBlock').onclick();"""
    for f in fieldsFromDB:
        attackString += """
        setValueById('%s' + maxAttack, '%s');""" % (f, cleanquotes(attack[f]))


populateCombatTabString = """
function populateCombatTab()
{
    %(abilCombat)s
    %(attacks)s
    recalcAll();
}
""" % {'abilCombat':abilCombatString, 'attacks':attackString}

f = open('xsheet-combattab-template.js', 'r')
combatTabTemplate = f.read()
f.close()

combatTabText = combatTabTemplate % {'populateCombatTab' : populateCombatTabString}

print "Content-Type: text/plain\n\n"
print combatTabText